package org.example.aienglishapp.service.article;

import jakarta.transaction.Transactional;
import org.example.aienglishapp.entity.article.Article;
import org.example.aienglishapp.entity.article.Translation;
import org.example.aienglishapp.mapper.article.ArticleMapper;
import org.example.aienglishapp.mapper.article.TranslationMapper;
import org.example.aienglishapp.config.others.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Transactional
@Service
public class TranslationServiceImpl implements TranslationService {

    private static final Logger logger = LoggerFactory.getLogger(TranslationServiceImpl.class);

    @Autowired
    private TranslationMapper translationMapper;

    @Autowired
    private BaiduFanyiService baiduFanyiService;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private RedisService redisService;

    private static final String TRANSLATION_CACHE_PREFIX = "translation:article:";

    @Override
    public void addTranslation(Translation translation) {
        try {
            // 将翻译记录插入数据库
            translationMapper.insertTranslation(translation);
            logger.info("Translation added to DB: {}", translation);

            // 同时将翻译数据存入 Redis 缓存
            redisService.set(TRANSLATION_CACHE_PREFIX + translation.getArticleId(), translation);
            logger.info("Translation added to Redis cache: {}", translation);
        } catch (Exception e) {
            logger.error("Error adding translation: {}", e.getMessage(), e);
            throw e; // 重新抛出异常，触发事务回滚
        }
    }

    @Override
    public void updateTranslation(Translation translation) {
        try {
            // 更新数据库中的翻译记录
            translationMapper.updateTranslation(translation);
            logger.info("Translation updated in DB: {}", translation);

            // 更新 Redis 缓存中的翻译数据
            redisService.set(TRANSLATION_CACHE_PREFIX + translation.getArticleId(), translation);
            logger.info("Translation updated in Redis cache: {}", translation);
        } catch (Exception e) {
            logger.error("Error updating translation: {}", e.getMessage(), e);
            throw e; // 重新抛出异常，触发事务回滚
        }
    }

    @Override
    public void deleteTranslation(Long id) {
        try {
            // 删除数据库中的翻译记录
            translationMapper.deleteTranslationById(id);
            logger.info("Translation deleted from DB with ID: {}", id);

            // 同时删除 Redis 缓存中的翻译数据
            redisService.delete(TRANSLATION_CACHE_PREFIX + id);
            logger.info("Translation deleted from Redis cache with ID: {}", id);
        } catch (Exception e) {
            logger.error("Error deleting translation with ID {}: {}", id, e.getMessage(), e);
            throw e; // 重新抛出异常，触发事务回滚
        }
    }

    @Override
    public void deleteTranslationByArticleId(Long articleId) {
        try {
            // 删除数据库中与文章关联的翻译记录
            translationMapper.deleteTranslationByArticleId(articleId);
            logger.info("Translations deleted from DB for article ID: {}", articleId);

            // 删除 Redis 缓存中的翻译数据
            redisService.delete(TRANSLATION_CACHE_PREFIX + articleId);
            logger.info("Translations deleted from Redis cache for article ID: {}", articleId);
        } catch (Exception e) {
            logger.error("Error deleting translations for article ID {}: {}", articleId, e.getMessage(), e);
            throw e; // 重新抛出异常，触发事务回滚
        }
    }

    @Override
    public Translation getTranslationById(Long id) {
        // 先从 Redis 中获取翻译记录
        Translation translation = (Translation) redisService.get(TRANSLATION_CACHE_PREFIX + id);
        if (translation != null) {
            logger.info("Fetched translation from Redis with ID: {}", id);
            return translation;
        }

        // 如果 Redis 中没有，再从数据库中查询
        translation = translationMapper.getTranslationById(id);
        if (translation != null) {
            // 将查询到的翻译数据缓存到 Redis 中
            redisService.set(TRANSLATION_CACHE_PREFIX + id, translation);
            logger.info("Fetched translation from DB with ID: {} and cached in Redis", id);
        }
        return translation;
    }

    @Override
    public List<Translation> getAllTranslations() {
        List<Translation> translations = translationMapper.getAllTranslations();
        logger.info("Fetched all translations from DB, total count: {}", translations.size());
        return translations;
    }

    @Override
    public Translation getTranslationByArticleId(Long articleId) {
        // 先从 Redis 中获取翻译记录
        Translation translation = (Translation) redisService.get(TRANSLATION_CACHE_PREFIX + articleId);
        if (translation != null) {
            logger.info("Fetched translation from Redis for article ID: {}", articleId);
            return translation;
        }

        // 如果 Redis 中没有，再从数据库中查询
        translation = translationMapper.getTranslationByArticleId(articleId);
        if (translation != null) {
            // 将查询到的翻译数据缓存到 Redis 中
            redisService.set(TRANSLATION_CACHE_PREFIX + articleId, translation);
            logger.info("Fetched translation from DB for article ID: {} and cached in Redis", articleId);
        }
        return translation;
    }

    @Override
    public Translation translateAndSave(Long articleId) {
        logger.info("Translating article ID {}: title and text", articleId);

        // 检查 Redis 缓存中是否已有翻译数据
        Translation cachedTranslation = (Translation) redisService.get(TRANSLATION_CACHE_PREFIX + articleId);
        if (cachedTranslation != null) {
            logger.info("Translation already exists in cache for article ID: {}", articleId);
            return cachedTranslation; // 如果 Redis 中已有翻译，直接返回
        }

        // 根据 articleId 查找对应的文章
        Article article = articleMapper.getArticleById(articleId);
        if (article == null) {
            logger.error("Article with ID {} not found", articleId);
            throw new RuntimeException("Article not found with ID: " + articleId);
        }

        // 检查文章正文长度是否符合要求
        if (article.getOriginalText() == null || article.getOriginalText().length() > 5000) {
            throw new IllegalArgumentException("文章正文不能超过5000个字符");
        }

        // 模拟延时请求（例如延迟 2 秒）
        try {
            logger.info("Simulating delay before translation...");
            Thread.sleep(2000); // 延迟 2 秒
        } catch (InterruptedException e) {
            logger.error("Error during delay before translation: {}", e.getMessage());
        }

        // 使用百度翻译服务翻译标题和正文
        String translatedTitle = null;
        String translatedText = null;

        try {
            logger.debug("Translating title: {}", article.getTitle());
            translatedTitle = baiduFanyiService.translate(article.getTitle(), "auto", "zh");

            // 延时请求到百度翻译服务
            try {
                logger.info("Adding delay before translating text...");
                Thread.sleep(2000);  // 延迟 2 秒
            } catch (InterruptedException e) {
                logger.error("Error during delay before text translation: {}", e.getMessage());
            }

            logger.debug("Translating text: {}", article.getOriginalText());
            translatedText = baiduFanyiService.translate(article.getOriginalText(), "auto", "zh");

            logger.info("Successfully translated article ID {}: Title = {} => {} , Text = {} => {}",
                    articleId, article.getTitle(), translatedTitle, article.getOriginalText(), translatedText);

        } catch (Exception e) {
            logger.error("Error occurred during translation for article ID {}: {}", articleId, e.getMessage());
            throw new RuntimeException("Translation error for article ID " + articleId, e);
        }

        // 创建翻译记录并保存
        Translation translation = new Translation();
        translation.setArticleId(articleId);
        translation.setTranslatedTitle(translatedTitle);
        translation.setTranslatedText(translatedText);
        translation.setStatus("translated");

        // 将翻译记录保存到数据库
        addTranslation(translation);
        logger.info("Translation for article ID {} saved: {}", articleId, translation);

        // 将翻译记录存入 Redis 缓存
        redisService.set(TRANSLATION_CACHE_PREFIX + articleId, translation);
        return translation;
    }
}